source("useful.R")
       
## use the early subset of the Degen & Tanenhaus data
# set your path here
load("processed_data/dt.RData")
dt = subset(dt, POD == "early")

######################################
## plot mean total dwell time on different regions in a time window relative to a linguistic event of interest 
## TODO generalize getDwellTime() function
## TODO plot mean _first_, rather than _total_ dwell time
######################################


######################################
## 400ms window after quantifier onset +200ms
dat = dt[dt[,"Time_rel_stim_Qonset"] >= 200 & dt[,"Time_rel_stim_Qonset"] <= 600,]
dat = dat[dat[,"rp_RegionType"] %in% c("c","t"),]
dat = droplevels(dat)
# unique condition combinations
uni = unique(paste(dt$TrialDataID,dt$Quantifier,dt$Numbers,dt$TargetSize))
t = as.data.frame(table(dat[,c("TrialDataID","rp_RegionType","Quantifier","Numbers","TargetSize")]))
t$Cond = paste(t$TrialDataID,t$Quantifier,t$Numbers,t$TargetSize)
t = subset(t, t$Cond %in% uni)
agr = with(t,aggregate(Freq,by=list(Quantifier,rp_RegionType,Numbers,TargetSize),FUN=mean))#,FUN=mean))
colnames(agr) = c("Quantifier","Region","Numbers","TargetSize","MeanTimeSteps")
agr$Time = agr$MeanTimeSteps*20
agr$SE = with(t,aggregate(Freq,by=list(Quantifier,rp_RegionType,Numbers,TargetSize),FUN=se))$x*20
agr$YMin = agr$Time - agr$SE
agr$YMax = agr$Time + agr$SE
dodge = position_dodge(.9)  

p.after = ggplot(agr, aes(x=TargetSize,y=Time,fill=Region)) +
  geom_bar(stat="identity",position=dodge) +
  geom_errorbar(aes(ymin=YMin,ymax=YMax),width=0.25,position=dodge) +
  facet_grid(Quantifier~Numbers)
p.after
######################################

######################################
## 400ms window before quantifier onset +200ms
dat = dt[dt[,"Time_rel_stim_Qonset"] >= -200 & dt[,"Time_rel_stim_Qonset"] <= 200,]
dat = dat[dat[,"rp_RegionType"] %in% c("c","t"),]
dat = droplevels(dat)
# unique condition combinations
uni = unique(paste(dt$TrialDataID,dt$Quantifier,dt$Numbers,dt$TargetSize))
t = as.data.frame(table(dat[,c("TrialDataID","rp_RegionType","Quantifier","Numbers","TargetSize")]))
t$Cond = paste(t$TrialDataID,t$Quantifier,t$Numbers,t$TargetSize)
t = subset(t, t$Cond %in% uni)
agr = with(t,aggregate(Freq,by=list(Quantifier,rp_RegionType,Numbers,TargetSize),FUN=mean))#,FUN=mean))
colnames(agr) = c("Quantifier","Region","Numbers","TargetSize","MeanTimeSteps")
agr$Time = agr$MeanTimeSteps*20
agr$SE = with(t,aggregate(Freq,by=list(Quantifier,rp_RegionType,Numbers,TargetSize),FUN=se))$x*20
agr$YMin = agr$Time - agr$SE
agr$YMax = agr$Time + agr$SE
dodge = position_dodge(.9)  

p.before = ggplot(agr, aes(x=TargetSize,y=Time,fill=Region)) +
  geom_bar(stat="identity",position=dodge) +
  geom_errorbar(aes(ymin=YMin,ymax=YMax),width=0.25,position=dodge) +
  facet_grid(Quantifier~Numbers)
p.before

# Problems with this way of looking at the data?


